package com.itheima.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Service.SetmealService;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.dao.SetmealAndCheckGroupDao;
import com.itheima.dao.SetmealDao;
import com.itheima.pojo.Setmeal;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private SetmealAndCheckGroupDao setmealAndCheckGroupDao;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${freemarker.out.path}")
    private String outPutPath;

    /**
     * 图片上传
     * @param imgFile
     * @return
     */
    @Override
    public String upload(MultipartFile imgFile) throws IOException {
        byte[] bytes = imgFile.getBytes();

        String imgName= imgFile.getOriginalFilename(); //获取文件名字
        String uuid = UUID.randomUUID().toString(); //获取唯一字符串，用于拼接名字
        String suffix = imgName.substring(imgName.lastIndexOf(".")); //获取后缀名
        String fileName=uuid+suffix;

        String imgUrl= aliOssUtil.upload(bytes, fileName);
        return imgUrl;
    }

    /**
     * 套餐添加
     * @param checkgroupIds
     * @param setmeal
     * @return
     */
    @Override
    @Transactional
    public void add(String checkgroupIds, Setmeal setmeal) {
        //添加套餐,需要返回id
        setmealDao.insert(setmeal);
        //checkgroupIds为空就不用添加了
        if (checkgroupIds==null || checkgroupIds.equals("") ){
            return;
        }else {
            //添加关联检查组
            String[] splits = checkgroupIds.split(",");
            for (String split : splits) {
                Integer checkGroupId= Integer.parseInt(split);
                setmealAndCheckGroupDao.insert(setmeal.getId(),checkGroupId);
            }
        }
        if (setmeal.getImg() != null) {
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        }
        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）---------------------------
//        generateMobileStaticHtml();
    }


    /**
     * 编辑套餐
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Setmeal setmeal, String checkgroupIds) throws Exception {
        //1.根据id编辑套餐
        setmealDao.update(setmeal);

        if (checkgroupIds ==null || checkgroupIds.equals("")){
            throw new Exception("checkgroupIds为空,放弃更新");
        }
        //根据setmealId 删除关联表
        setmealAndCheckGroupDao.delete(setmeal.getId());

        //加回关联表
        String[] checkGroupIdsArray = checkgroupIds.split(",");
        for (String checkGroupId : checkGroupIdsArray) {
            setmealAndCheckGroupDao.insert(setmeal.getId(),Integer.parseInt(checkGroupId));
        }
    }
    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(String id) {
        Setmeal setmeal= setmealDao.findById(Integer.parseInt(id));
        return setmeal;
    }
    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //1.先分号页，然后查数据库，接着封装成Page《T》类型，传回total与rows
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        List<Setmeal> setmealList = setmealDao.findByString(queryPageBean.getQueryString());

        Page<Setmeal> page=(Page<Setmeal>) setmealList;

        return new PageResult(page.getTotal(),page.getResult());
    }

//-------------------------freeMaker-模板----------------------------------------------

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealDao.findAll();
        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById4Detail(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }



}
